/*
 * @Author: songwh
 * @Date: 2017-06-15 17:54:06
 * @Last Modified by: songwh
 * @Last Modified time: 2017-06-27 09:41:09
 */

import GaoUpdate from '../open-ad-update/open-ad-update.vue'
import Pages from '../../pages/pages.vue'
import { getOpenAdList, deleteOpenAd, swapOpenAd, showMsg } from '../../../vuex/action'
import extend from 'extend'

const swapList = (fromId, toId, list) => {
  var idOrder = []
  var listObj = {}
  var newList = []

  for (let index in list) {
    let banner = list[index]
    listObj[banner.id] = banner
    if (banner.id === fromId) {
      idOrder.push(toId)
    } else if (banner.id === toId) {
      idOrder.push(fromId)
    } else {
      idOrder.push(banner.id)
    }
  }

  idOrder.forEach((id) => {
    newList.push(listObj[id])
  })

  return newList
}

export default {
  name: 'GaoList',
  props: ['position', 'title'],
  components: {
    'vue-gao-update': GaoUpdate,
    'vue-pages': Pages
  },
  data() {
    return {
      list: [],
      location: '',
      securityCode: '',
      pages: {
        start: 0,
        totalPages: 0,
        limit: 20
      }
    }
  },
  ready() {
    this.getList({})
  },
  vuex: {
    getters: {
      fresh: state => state.gaoListNeedFresh
    },
    actions: {
      xShowMsg: showMsg,
      xGetAdList: getOpenAdList,
      xDeleteAd: deleteOpenAd,
      xSwapAd: swapOpenAd
    }
  },
  methods: {
    deepClone(data) {
      return extend(true, {}, data)
    },
    deleteAd(id) {
      this.xDeleteAd(id)
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    },
    getList({start=this.pages.start, limit=this.pages.limit}) {
      this.xGetAdList({
        position: this.position,
        start: start,
        limit: limit
      })
        .then((data) => {
          this.list = data.list
          this.securityCode = data.securityCode
          this.location = data.location
          this.pages.totalPages = Math.ceil(data.totalCount / limit)
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    },
    swap(fromId, toId) {
      this.xSwapAd({
        fromId: fromId,
        toId: toId
      })
        .then(() => {
          this.list = swapList(fromId, toId, this.list)
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  },
  watch: {
    fresh() {
      if (this.fresh) {
        this.getList({})
      }
    }
  }
}
